import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import '../../utils/G.dart';
import '../../utils/widgets/my_sliver_delegate.dart';

class ProductComment extends StatefulWidget {
  String id;
  ProductComment({
    Key? key,
    required String this.id,
  }) : super(key: key);

  @override
  _ProductCommentState createState() => _ProductCommentState();
}

class _ProductCommentState extends State<ProductComment> {
  List list = [];
  int page = 1;
  int type = 0;

  List types = [
    {'key': 0, 'title': '全部'},
    {'key': 1, 'title': '好评'},
    {'key': 2, 'title': '中评'},
    {'key': 3, 'title': '差评'},
  ];
  int currentIndex = 0;

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _onRefresh();
  }

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 1000));
    var res = await G.api.product.comment(id: widget.id, page: 1, type: type);
    if (res['status'] == 200) {
      list = res['data'];
    }
    if (mounted) {
      setState(() {});
    }

    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    page++;
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    var res =
        await G.api.product.comment(id: widget.id, page: page, type: type);
    if (res['status'] == 200) {
      list.addAll(res['data']);
    }

    if (mounted) {
      setState(() {});
    }

    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('评论列表'),
          centerTitle: true,
        ),
        // body: Text(widget.cate_name)
        body: _renderFreshList());
  }

  Widget _renderFreshList() {
    return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const WaterDropHeader(),
        footer: const ClassicFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          slivers: [
            // 具有吸顶效果的导航菜单
            SliverPersistentHeader(
                pinned: true, // 吸顶
                floating: false, // 反向滚动时，内容是否立即变大
                delegate: MySliverDelegate(
                    minHeight: 50,
                    maxHeight: 50,
                    child: Container(
                        height: 50,
                        child: ListView.builder(
                            itemCount: types.length,
                            scrollDirection: Axis.horizontal,
                            itemBuilder: (cxt, index) {
                              return _renderType(index);
                            })))),
            SliverPadding(
              padding: const EdgeInsets.all(10.0),
              sliver: _renderList(),
            )
          ],
        ));
  }

  Widget _renderType(int i) {
    return GestureDetector(
        child: Container(
            width: G.width / types.length,
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 10),
            decoration: BoxDecoration(
                color: currentIndex == i
                    ? Colors.blue.shade100
                    : Colors.grey.shade100,
                border: Border(
                    bottom: BorderSide(
                  width: 3,
                  color: currentIndex == i
                      ? Colors.blue.shade200
                      : Colors.grey.shade100,
                ))),
            child: Text(types[i]['title'],
                style: TextStyle(
                    color: currentIndex == i
                        ? Theme.of(context).primaryColor
                        : Colors.black45,
                    fontWeight:
                        currentIndex == i ? FontWeight.w600 : FontWeight.w400,
                    fontSize: 16))),
        onTap: () {
          currentIndex = i;
          type = types[i]['key'];

          // 重新发送请求
          _onRefresh();
        });
  }

  // 渲染列表
  Widget _renderList() {
    // if (isList) {
    //   return MyList(list: list);
    // } else {
    //   return MyGrid(list: list);
    // }
    // return Text('评论列表');
    return SliverList(
      delegate: SliverChildBuilderDelegate((context, index) {
        // print('============='+index.toString());
        var item = list[index];
        return _renderCommentItem(item);
      }, childCount: list.length),
    );
  }

  Widget _renderCommentItem(Map item) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      padding: const EdgeInsets.fromLTRB(0, 0, 0, 20),
      child: Flex(
        direction: Axis.horizontal,
        children: [
          G.imageWidget(item['avatar'], width: 70, height: 70),
          Expanded(
              child: Container(
            height: 70,
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      item['nickname'],
                      style: const TextStyle(fontSize: 16),
                      overflow: TextOverflow.ellipsis,
                    ),

                    // 五星评价
                    RatingBar.builder(
                      initialRating:
                          (item['product_score'] + item['service_score']) / 2,
                      itemSize: 16,
                      minRating: 1,
                      direction: Axis.horizontal,
                      allowHalfRating: true,
                      itemCount: 5,
                      itemPadding: const EdgeInsets.symmetric(horizontal: 1.0),
                      itemBuilder: (context, _) => const Icon(
                        Icons.star,
                        color: Colors.amber,
                      ),
                      ignoreGestures: true, // 忽略手势操作
                      onRatingUpdate: (rating) {
                        print(rating);
                      },
                    ),
                  ],
                ),
                Container(
                  child: Wrap(
                    direction: Axis.horizontal,
                    children: [
                      Text(
                        item['comment'],
                        style: const TextStyle(fontSize: 16),
                      )
                    ],
                  ),
                ),
                Row(
                  children: [
                    Container(
                      child: Text(
                        item['add_time'],
                        style:
                            const TextStyle(fontSize: 14, color: Colors.grey),
                      ),
                    )
                  ],
                )
              ],
            ),
          ))
        ],
      ),
    );
  }
}
